package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Service service;

    public RequestProcessor(Socket socket, Service service) {
        this.socket = socket;
        this.service = service;
    }

    @Override
    public void run() {
        try{

            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String hostStr = request.getHeader("host");
            hostStr = hostStr.substring(0, hostStr.indexOf(":"));
            Host host = service.getEngine().getHost(hostStr);

            String url = request.getUrl();
            if (url.startsWith("/")) {
                url = url.substring(1);
            }
            String[] urlPieces = url.split("/");
            String contextPath = urlPieces[0];
            String wrapperPath = url.substring(contextPath.length());


            Context context = host.getContext(contextPath);

            Wrapper wrapper = context.getWrapper(wrapperPath);

            // 静态资源处理
            if(wrapper == null) {
                response.outputHtml(context.getDocBase() + wrapperPath);
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = (HttpServlet) wrapper.getServlet();
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
